package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	. "liteblog/src/model"
	"log"
	"net/http"
	"strconv"
)

type RtnMsg struct {
	Status string `json:"status"`
	Pager  Pager  `json:"pager"`
}
type Pager struct {
	Messages []Message `json:"messages"`
	Page     int       `json:"page"`
	Pages    int       `json:"pages"`
}

func GetMsgPage(c *gin.Context) {
	pageid := c.Params.ByName("pageid")
	fmt.Println(pageid)
	pid, _ := strconv.Atoi(pageid)
	c.Request.ParseForm()
	searchValue := c.Request.Form.Get("searchValue")
	msg := &Message{}
	msgs, total, err := msg.SearchByPage(pid, searchValue)
	if err != nil {
		log.Panicln(err)
	}
	if msgs==nil{
		emptymsg := []Message{}
		msgs = emptymsg
	}
	rtnMsg := &RtnMsg{
		Status: "success",
		Pager: Pager{
			Page:     pid,
			Pages:    total/10 + 1,
			Messages: msgs,
		},
	}
	c.JSON(http.StatusOK, rtnMsg)
}

func InsertMsg(c *gin.Context) {
	c.Request.ParseForm()
	author := c.Request.Form.Get("author")
	content := c.Request.Form.Get("content")
	log.Println(author, content)
	msg := &Message{
		Name:    author,
		Content: content,
	}
	err := msg.Insert()
	if err != nil {
		log.Panicln(err)
	}
}
